<template>
  <div class="pay-page" v-if="order.id">
    <el-card shadow="never">
      <template #header>
        <div class="header">
          <span>订单支付</span>
          <el-icon class="close" @click="goBack"><Close /></el-icon>
        </div>
      </template>

      <!-- 订单信息 -->
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单号">#{{ order.id }}</el-descriptions-item>
        <el-descriptions-item label="桌台">{{ order.tableId ?? '打包' }}</el-descriptions-item>
        <el-descriptions-item label="下单时间">{{ new Date(order.createTime).toLocaleString() }}</el-descriptions-item>
        <el-descriptions-item label="应付金额">
          <span class="amount">¥{{ order.totalPrice.toFixed(2) }}</span>
        </el-descriptions-item>
      </el-descriptions>

      <!-- 菜品列表 -->
      <el-divider>菜品明细</el-divider>
      <div v-for="it in order.items" :key="it.dishId" class="dish-row">
        <span>{{ it.dishName }}</span>
        <span>× {{ it.quantity }}</span>
        <span>¥{{ (it.price * it.quantity).toFixed(2) }}</span>
      </div>

      <!-- 支付方式 -->
      <el-divider>选择支付方式</el-divider>
      <el-radio-group v-model="channel">
        <el-radio label="WECHAT">微信支付</el-radio>
        <el-radio label="ALIPAY">支付宝</el-radio>
      </el-radio-group>

      <!-- 按钮 -->
      <div class="action-bar">
        <el-button type="primary" size="large" @click="doPay">确认支付</el-button>
        <el-button size="large" @click="goBack">暂不支付</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { payOrder } from '@/api/order'
import { getOrderDetail } from '@/api/order'
import type { MyOrderVO } from '@/api/order'
import { Close } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const order = ref<MyOrderVO>({} as MyOrderVO)
const channel = ref('WECHAT')

/* 加载订单详情 */
onMounted(async () => {
  const { data: res } = await getOrderDetail(Number(route.params.orderId))
order.value = res.data   // ← 只拿 data 字段
})

/* 支付 */
async function doPay() {
  try {
    await payOrder(order.value.id,channel.value)
    ElMessage.success('支付成功')
    router.replace('/customer/my-order')
  } catch (e: any) {
    ElMessage.error(e.response?.data?.message || '支付失败')
  }
}

function goBack() {
  router.back()
}
</script>

<style scoped>
.pay-page {
  max-width: 600px;
  margin: 40px auto;
  padding: 0 16px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.close {
  cursor: pointer;
  font-size: 18px;
}

.amount {
  color: #f56c6c;
  font-weight: 600;
  font-size: 18px;
}

.dish-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 6px;
}

.action-bar {
  margin-top: 24px;
  text-align: center;
}
</style>